package lesson01;

import java.util.Random;

/**
 *  实现多线程数组求和.
 *
 * @author wileda
 * @date 2023/01/10  11:32
 */
public class Demo09 {
    static int sum1 = 0;
    static int sum2 = 0;
    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        int[] arr = new int[1000_0000];
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (random.nextInt(100) + 1);
        }

        Thread t1 = new Thread(() -> {
             sum1 = 0;
            for (int i = 0; i < arr.length; i += 2) {
                sum1 += arr[i];
            }
        });

        Thread t2 = new Thread(() -> {
             sum2 = 0;
            for (int i = 1; i < arr.length ; i += 2) {
                sum2 += arr[i];
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        int sum = sum1 + sum2;
        System.out.println("偶数和为：" + sum1);
        System.out.println("奇数和为：" + sum2);
        System.out.println("总和为：" + sum);
        long endTime = System.currentTimeMillis();
        System.out.println("耗费时间为：" + (endTime - startTime) + "ms");
    }
}

